/*
 * @Description:
 * @Version: 2.0
 * @Autor: wushiyang
 * @Date: 2022-05-24 09:44:58
 * @LastEditors: zhou
 * @LastEditTime: 2022-07-02 16:31:37
 */
// 兼容wangeditor的标签格式
let is_img

function renderHtml(content, is_img_hidden = false) {
    is_img = is_img_hidden
    try {
        if (typeof content === 'string') {
            content = content.replace('&lt;br/&gt;', '<br/>')
            return renderNodes(JSON.parse(content));
        }
        return renderNodes(content);
    } catch (e) {
        return content;
    }
}

function renderNode(node) {
    if (typeof node === 'string') {
        // node = node.replace('&lt;br/&gt;', '<br/>')
        if (node.indexOf('<br/>') > -1 || node.indexOf('<script>') > -1) {
            return '';
        }
        return node;
    }
    const { tag, children, attrs } = node;
    const attrsArr = [];
    if (tag === 'script') {
        return '';
    }
    if(is_img && tag == 'img') { return ''}   // 去掉图片
    if (Array.isArray(attrs)) {
        attrs.forEach(({ name, value }) => {
            attrsArr.push(`${name}="${value}"`);
        });
    }
    return `<${tag} ${attrsArr.join(' ')}>${renderNodes(children)}</${tag}>`;
}

function renderNodes(nodes) {
    if (!Array.isArray(nodes)) {
        return JSON.stringify(nodes);
    }
    return nodes.map(item => renderNode(item)).join('');
}

export {
    renderHtml
}
